<template>
  <div class="server-main">
    <el-form :inline="true" v-model="modelData" class="search-form">
      <el-form-item label="测试对象" class="form-input">
        <el-input v-model.trim="modelData.objectName" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="onSubmit(1)"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">测试对象管理</span>
        <div>
          <el-upload
            class="upload-demo"
            :action="`${this.$api.resultAnalyse.zehaoObj.fileUpload}`"
            multiple
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <el-button size="small" type="primary">导入测试结果</el-button>
          </el-upload>
        </div>
      </div>
      <el-table :data="testList" class="km-table">
        <el-table-column
          type="index"
          label="ID"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="objectName"
          label="测试对象名称"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="caseCount"
          label="测试用例数量"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="resultCount"
          label="测试结果数量"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="defectDetection"
          label="缺陷检测率（%）"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="testCoverage"
          label="测试覆盖率（%）"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="resultType"
          label="类型"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="testTurn"
          label="测试轮次"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="导入时间"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="openEditResult(scope.row)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="analiyies(scope.row.resultId)"
              >详情</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="openAnalysePop(scope.row)"
              >分析</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click="delete1(scope.row.resultId)"
              >删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="km-pagination"
        background
        :small="true"
        layout="total, prev, pager, next,sizes, jumper"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="modelData.pageSize"
        :pager-count="7"
        :page-sizes="[10, 20, 30]"
        :current-page="modelData.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="dialogConfig[dialogType].title"
      :visible.sync="dialogFormVisible"
      @close="afterDialogClose"
    >
      <el-form
        :model="modelParams"
        :rules="rules"
        ref="dialogForm"
        label-position="right"
        label-width="120px"
        :inline="true"
      >
        <el-form-item
          label="测试检测率:"
          prop="defectDetection"
          class="dialog-inline"
        >
          <el-input v-model.number="modelParams.defectDetection"></el-input>
        </el-form-item>
        <span :style="{ height: '30px', lineHeight: '38px' }">%</span>
        <el-form-item
          label="测试覆盖率:"
          prop="testCoverage"
          class="dialog-inline"
        >
          <el-input v-model.number="modelParams.testCoverage"> </el-input>
        </el-form-item>
        <span :style="{ height: '30px', lineHeight: '38px' }">%</span>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- zhurh  22/1/13   分析柱状图弹窗 -->
    <el-dialog
      title="统计分析"
      v-if="analyseChartsVisible"
      :visible.sync="analyseChartsVisible"
      @close="afterDialogClose"
      width="70%"
      top="10vh"
    >
      <div class="el-dialog-div">
        <BarChart id="analiyseChart" :dataList="chartsList"> </BarChart>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm" type="primary">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="批量导入"
      :visible.sync="uploadFormVisible"
      @close="afterDialogClose"
    >
      <div class="upload-hint">
        请选择需要导入的本体文件，仅支持文件格式为.xls、.xlsx、.csv的文件。
      </div>
      <el-form
        :model="uploadParams"
        :rules="uploadRules"
        ref="uploadForm"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="选择文件:" prop="fileName" class="dialog-inline">
          <el-input v-model="uploadParams.fileName" readonly>
            <template slot="append">
              <el-upload
                class="upload-demo"
                accept=".xls,.xlsx,.csv"
                :before-upload="beforeUpload"
                :show-file-list="false"
              >
                <el-button type="primary">选择文件</el-button>
              </el-upload>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitUploadForm" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import BarChart from "../../components/charts/barChart.vue";
export default {
  name: "OntologyManagement",
  components: { BarChart },
  data: () => {
    return {
      modelData: {
        objectName: "", //测试对象名称
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      deleteModel: {
        resultId: "",
      },
      testList: [],
      chartsList: [],
      tableList: [], // 本体列表
      total: 0, // 数据总条数
      loading: false,
      dialogFormVisible: false,
      uploadFormVisible: false,
      analyseChartsVisible: false, //zhurh -- 分析柱状图弹窗显隐控制变量
      editOntologyId: null, // 编辑本体的id
      fileModel: {
        file_url: "",
      },
      modelParams: {
        resultId: "",
        defectDetection: "", // 本体名称
        testCoverage: "", // 本体描述
      },
      dialogType: "ADD",
      dialogConfig: {
        ADD: {
          title: "创建本体",
          funcName: "createOntology",
        },
        EDIT: {
          title: "测试结果编辑",
          funcName: "editOntology",
        },
      },
      rules: {
        ontologyAllName: [
          {
            required: true,
            message: "请输入本体名称",
            trigger: "blur",
          },
        ],
        ontologyAllDescribe: [
          {
            required: true,
            message: "请输入本体描述",
            trigger: "blur",
          },
        ],
        defectDetection: [
          {
            required: true,
            message: "检测率不能为空",
            trigger: "blur",
          },
        ],
        testCoverage: [
          {
            required: true,
            message: "覆盖率不能为空",
            trigger: "blur",
          },
        ],
      },
      uploadRules: {
        fileName: [
          {
            required: true,
            message: "请选择本体文件",
            trigger: ["change", "blur"],
          },
        ],
      },
      textSizeConfig: {
        minRows: 4,
        maxRows: 10,
      },
      uploadParams: {
        fileName: null,
      },
    };
  },
  computed: {
    ...mapState({
      containerDom: (state) => state.server.containerDom,
    }),
  },
  created() {
    this.getModelList();
    // 获取本体列表
  },
  methods: {
    ...mapMutations({
      // save_allGraphData: "ontologyModel/save_allGraphData",
      save_ontologyAllId: "ontologyModel/save_ontologyAllId",
    }),
    // 获取事件查询列表
    getModelList() {
      let params = this.modelData;
      this.$axios
        .post(this.$api.resultAnalyse.zehaoObj.getModelList, params)
        .then((res) => {
          console.log("res", res);
          let data = res.data.data.list;
          this.total = res.data.data.total;
          this.testList = data;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    deleteResult() {
      let params = this.deleteModel;
      this.$confirm("是否确认删除此记录？删除后无法恢复。", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post(this.$api.resultAnalyse.zehaoObj.deleteResult, params)
            .then((res) => {
              this.getModelList();
            })
            .catch((err) => {
              console.error(err);
            });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 查询
    onSubmit(pageNum) {
      this.modelData.pageNum = pageNum ? pageNum : this.modelData.pageNum;
      this.getModelList();
    },
    //分析
    analiyies(resultId) {
      this.$router.push({
        path: "/resultAnalyse/reultManagementList",
        query: {
          resultId,
        },
      });
    },
    // 修改当前页码
    handleCurrentChange(page) {
      this.modelData.pageNum = page;
      this.getModelList();
    },
    //修改当前页面容量
    handleSizeChange(page) {
      this.modelData.pageSize = page;
      this.getModelList();
    },
    //删除测试对象
    delete1(id) {
      console.log("id", id);
      this.deleteModel.resultId = id;
      this.deleteResult();
      this.getModelList();
    },
    // 跳转详情页
    goDetail(id) {
      this.$router.push(`/ontologyModel/ontologyManagement/edit/${id}`);
      this.save_ontologyAllId(id);
    },
    //处理文件上传
    handleAvatarSuccess(res, file) {
      console.log("url", res);
      this.fileModel.file_url = res;
      let params = this.fileModel;
      this.$axios
        .post(this.$api.resultAnalyse.zehaoObj.handleResultFile, params)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.warning("导入成功");
            this.getModelList();
          } else {
            this.$message.warning("导入失败");
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 打开编辑本体框
    openEditResult(row) {
      let { resultId, defectDetection, testCoverage } = row;
      this.modelParams.defectDetection = defectDetection;
      this.modelParams.testCoverage = testCoverage;
      this.modelParams.resultId = resultId;
      this.dialogFormVisible = true;
      this.dialogType = "EDIT";
    },
    // zhurh--打开分析柱状图弹框
    openAnalysePop(row) {
      console.log(row);
      if (row && row.resultId) {
        this.getAnalyseData(row.resultId);
      }
      //
    },
    // zhurh--获取分析图数据
    getAnalyseData(id) {
      this.$axios
        .get(
          `${this.$api.resultAnalyse.zehaoObj.iaResultAnalyse}?resultId=${id}`
        )
        .then((res) => {
          console.log("res", res);
          let data = res.data.data;
          if (data.length > 0) this.chartsList = data;
          this.analyseChartsVisible = true;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 模态框关闭后
    afterDialogClose() {
      this.$refs.dialogForm && this.$refs.dialogForm.resetFields();
      this.$refs.uploadForm && this.$refs.uploadForm.resetFields();
    },
    // 取消
    resetDialogForm() {
      this.dialogFormVisible = false;
      this.uploadFormVisible = false;
      this.analyseChartsVisible = false;
    },
    // 确定
    submitDialogForm() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          console.log("param", JSON.stringify(this.modelParams));
          let func = this.dialogConfig[this.dialogType].funcName;
          this[func]();
          this.dialogFormVisible = false;
        } else {
          return false;
        }
      });
    },
    // 编辑本体
    editOntology() {
      let params = this.modelParams;
      // console.log('edit', params)
      this.loading = true;
      this.$axios
        .post(this.$api.resultAnalyse.zehaoObj.updateResult, params)
        .then((res) => {
          this.loading = false;
          this.$message.success("编辑成功");
          this.dialogFormVisible = false;
          this.onSubmit();
        })
        .catch((error) => {
          this.loading = false;
        });
      this.getModelList();
    },

    // 批量导入
    uploadModel(row) {
      this.uploadFormVisible = true;
      this.editOntologyId = row.ontologyAllId;
    },
    beforeUpload(file) {
      this.uploadParams.fileName = file.name;
      this.uploadFile = file;
      return false;
    },
    submitUploadForm() {
      this.loading = true;
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          let params = {
            file: this.uploadFile,
            ontologyAllId: this.editOntologyId,
          };
          this.$fileHttp
            .uploadFile(this.$api.ontologyModel.xuekuiObj.uploladModel, params)
            .then((res) => {
              let code = res.data.code;
              if (code !== 200) {
                let message = res.data.message;
                this.$message.warning(message);
              }
              this.loading = false;
              this.uploadFormVisible = false;
            });
        } else {
          this.loading = false;
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-dialog-div {
  height: 60vh;
  overflow: hidden;
  padding: 20px;
}
.server-main {
  position: relative;

  .search-form {
    background: #ffffff;
    border-radius: 4px;
    padding: 16px 32px;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      .el-input,
      .el-select {
        ::v-deep .el-input__inner {
          width: 240px;
          height: 32px;
          background: #ffffff;
          border-radius: 2px;
          border: 1px solid #e0e0e0;
        }
      }
    }
  }

  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    background: #ffffff;
    border-radius: 4px;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
      }

      margin-bottom: 10px;
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  ::v-deep .el-table__append-wrapper {
    padding: 10px;
  }

  ::v-deep .el-dialog {
    width: 500px;
    border-radius: 5px;
  }

  .dialog-inline {
    ::v-deep .el-form-item__content {
      width: 300px;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }

  .upload-hint {
    font-size: 12px;
    color: #aaa;
    text-align: center;
    line-height: 40px;
  }

  .upload-demo {
    display: inline-block;
    margin-left: 1rem;
  }
}
</style>
